package com.mikufufu.blog.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mikufufu.blog.common.cache.RedisCache;
import com.mikufufu.blog.common.constant.Constant;
import com.mikufufu.blog.common.constant.RedisKey;
import com.mikufufu.blog.model.entity.SysSetting;
import com.mikufufu.blog.service.SysSettingService;
import com.mikufufu.blog.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class VisitCountTask {

    @Autowired
    private SysSettingService sysSettingService;

    /**
     * 是否开启任务
     */
    @Value("${task.visit-count-task.enable:false}")
    private Boolean enable;

    /**
     * 固定速率执行
     * 任务从上一次开始执行的时间点开始计算，间隔固定的时间后再次执行。
     * fixedRate属性表示任务执行之间的时间间隔，单位为毫秒。
     * 每分钟执行一次
     */
    @Scheduled(fixedRateString = "${task.visit-count-task.fixed-rate:60000}",initialDelayString = "${task.visit-count-task.initial-delay:0}")
    public void run() {
        if (enable) {
            log.debug("开始执行访问量任务");
            this.task();
            log.debug("结束执行访问量任务");
        }
    }

    private void task() {
        Integer count = (Integer) RedisCache.get(RedisKey.VISIT_COUNT);
        if (count != null){
            SysSetting visitCount = sysSettingService.getOne(new LambdaQueryWrapper<SysSetting>().eq(SysSetting::getCode, Constant.GUEST_ROLE_COUNT_CODE));
            if (StringUtils.isEmpty(visitCount)){
                visitCount = new SysSetting();
                visitCount.setCode(Constant.GUEST_ROLE_COUNT_CODE);
                visitCount.setValue(String.valueOf(count));
                visitCount.setConfigName("访问量");
                visitCount.setRemark("访问量");
                visitCount.setStatus(0);
                sysSettingService.save(visitCount);
                return;
            }
            if (count.equals(Integer.parseInt(visitCount.getValue()))){
                return;
            }
            visitCount.setValue(String.valueOf(count));
            sysSettingService.updateById(visitCount);
        }
    }
}
